package com.sanpu.kxe.business.main.presenter;

import android.app.Activity;
import android.text.TextUtils;

import com.sanpu.kxe.business.main.bean.WxInfoOutput;
import com.sanpu.kxe.business.main.contract.MyWxInfoContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.module.luban.Luban;
import com.sanpu.kxe.module.luban.OnRenameListener;
import com.sanpu.kxe.utils.ToastUtil;
import com.sanpu.library.imagechoose.PhotoPicker;
import com.sanpu.library.imagechoose.PhotoPreview;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：我的微信
 * Created by 薛勇军 on 2018/7/11.
 */

public class MyWxInfoPresenter implements MyWxInfoContract.Presenter {

    private MyWxInfoContract.View mView;

    private CompositeSubscription mSubscription;

    private HashMap<String, File> imgFiles;

    public MyWxInfoPresenter(MyWxInfoContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
        imgFiles = new HashMap<>();
    }

    @Override
    public void userWxInfo() {
        mView.showLoadingDialog(false);
        Subscription subscription = MainModel.getInstance().getWxInfo()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WxInfoOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(WxInfoOutput wxInfoOutput) {
                        if (wxInfoOutput != null) {
                            if (!TextUtils.isEmpty(wxInfoOutput.getWxChatId())) {
                                mView.showWxChatId(wxInfoOutput.getWxChatId());
                            }
                            if (!TextUtils.isEmpty(wxInfoOutput.getWxQrcodeImg())) {
                                mView.showWxQrcodeImg(wxInfoOutput.getWxQrcodeImg());
                            }
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onCommit(String wxChatId) {
        //如果之前提交过微信信息，imgFiles可以为空
        mView.showLoadingDialog(true);
        Subscription subscription = MainModel.getInstance().postWxQrcode(wxChatId, imgFiles)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        ToastUtil.showTextViewPrompt("保存成功！");
                        ((Activity)mView.getContext()).finish();
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void picker(int requstCode) {
        PhotoPicker.builder().
                setPhotoCount(1)
                .setShowCamera(false)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start((Activity) mView.getContext(), requstCode);
    }

    @Override
    public void preview(String photo, int requstCode) {
        ArrayList<String> photoPaths = new ArrayList<>();
        photoPaths.add(photo);
        PhotoPreview.builder()
                .setPhotos(photoPaths)
                .setCurrentItem(0)
                .start((Activity) mView.getContext(), requstCode);
    }

    @Override
    public void onCompress(String filePath, final String reName) {
        mView.showLoadingDialog(false, "照片压缩处理中...");
        //同步方法请尽量避免在主线程调用以免阻塞主线程
        Observable.just(filePath)
                .observeOn(Schedulers.io())
                .map(new Func1<String, List<File>>() {
                    @Override
                    public List<File> call(String filePath) {
                        return luban(filePath, reName);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<File>>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(List<File> files) {
                        if (files != null && files.size()>0) {
                            imgFiles.put(reName, files.get(0));
                        }
                    }
                });
    }

    /**
     * luban图片压缩
     * @param filePath 图片地址
     * @param reName 重命名
     * @return
     */
    private List<File> luban(String filePath, final String reName) {
        try {
            // 同步方法直接返回压缩后的文件
            return Luban.with(mView.getContext())
                    .load(filePath)
                    .setRenameListener(new OnRenameListener() {
                        @Override
                        public String rename(String filePath) {
                            return reName + "_" + System.currentTimeMillis();
                        }
                    })
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void removeFile(String fileKey) {
        if (imgFiles != null && imgFiles.containsKey(fileKey)) {
            imgFiles.remove(fileKey);
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null)
            mView = null;
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (imgFiles != null) {
            imgFiles.clear();
            imgFiles = null;
        }
    }
}
